package com.eco.fanliapp.job.goodsjob;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.dao.AppGoodsMapper;
import com.eco.fanliapp.entity.*;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.service.impl.TaoBaoMethodServiceImpl;
import com.eco.fanliapp.utils.Convert;
import com.eco.fanliapp.utils.DateFormatUtils;
import com.eco.fanliapp.utils.StringUtils;
import com.eco.fanliapp.vo.AppGoodsFailure;
import com.eco.fanliapp.vo.HaoDanKuItemInfo;
import com.eco.fanliapp.vo.TbkItemInfoGetInfo;
import com.eco.fanliapp.vo.TbkPrivilegeGetInfo;
import com.eco.fanliapp.vo.respone.DTKResponse;
import com.eco.fanliapp.vo.respone.ResponeResults;
import com.taobao.api.internal.util.TaobaoUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.*;

/**
 * 商品的优惠券金额
 */
@DisallowConcurrentExecution
@PersistJobDataAfterExecution
public class HdkItemTask implements Job, Serializable {


    private static final Logger log = LoggerFactory.getLogger(HdkItemTask.class);

    @Autowired
    private IUserCashschemeService userCashschemeService;
    @Autowired
    private IAppGoodsService appGoodsService;
    @Autowired
    private ISySwitchService iSySwitchService;

    @Autowired
    private ITaoBaoService taoBaoService;

    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    RedisTemplateService redisTemplateService;
    @Autowired
    private AppGoodsMapper appGoodsMapper;
    @Autowired
    private ITaoBaoMethodService taoBaoMethodService;

    @Autowired
    private ISyLabelGoodsService syLabelGoodsService;
    @Autowired
    private FindItemIdUtils taoBaoUtils;

    public HdkItemTask() {
    }

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {

        //取得job详情
        JobDetail jobDetail = context.getJobDetail();

        JobDataMap dataMap = jobDetail.getJobDataMap();

        int executeCount = 0;
        if (dataMap.containsKey("runCount")) {
            executeCount = dataMap.getInt("runCount");
        }

        // 增量计数并将其存储回 JobDataMap，这样可以适当保持工作状态
        executeCount++;
        dataMap.put("runCount", executeCount);

        long startTime = System.currentTimeMillis();
        log.info("***************************************更新商品的优惠券金额 每5分钟一次-HdkItemTask：executeCount=" + executeCount + "--startTime=" + startTime);

        try {
            //当前时间
            Page<AppGoods> page = new Page<>(1, 1000);
            QueryWrapper<AppGoods> queryWrapper = new QueryWrapper<>();
            queryWrapper.ne("item_top", 2).ne("item_top", 3).ne("item_top", 7).ne("item_top", 8).eq("recommend", 1).orderByAsc("fanli_update_time");
//            queryWrapper.eq("recommend", 1).orderByAsc("fanli_update_time");

            IPage<AppGoods> appGoodsIPage = appGoodsService.page(page, queryWrapper);

            List<AppGoods> appGoodsUpdates = new ArrayList<>();
            List<AppGoods> appGoodsIndexUpdates = new ArrayList<>();
            AppCompany com = userCashschemeService.findCompanyAll();

            //需要删除的商品id
            StringBuilder needDeleteStr = new StringBuilder();
            //需要删除的商品
            List<AppGoodsFailure> appGoodsFailures = new ArrayList<>();

            if (appGoodsIPage != null && appGoodsIPage.getRecords() != null) {
                //商品id集合用于查询，每次最多40个
                String itemids = "";
                //商品id数量用于查询，每次最多40个
                int itemidsCount = 0;
                //商品id和tableid对照map
                Map<String, AppGoods> map = new HashMap<>();

                for (int i = 0; i < appGoodsIPage.getRecords().size(); i++) {

                    AppGoods appGoods = appGoodsIPage.getRecords().get(i);
                    if (appGoods.getItemTop() != null && appGoods.getItemTop() == 2 || appGoods.getItemTop() == 3) {
                        continue;
                    }
                    if (appGoods.getItemid() == null || "".equals(appGoods.getItemid())) {
                        continue;
                    }
                    itemids += appGoods.getItemid() + ",";
                    itemidsCount++;
                    map.put(appGoods.getItemid(), appGoods);
                    //如果凑够40条查询。
                    if (itemidsCount == 40 || i == (appGoodsIPage.getRecords().size() - 1)) {

                        itemidsCount = 0;//商品id数量用于查询，每次最多40个

                        Set<String> hasItemIdSet = new HashSet<>();

                        ServerResponse<List<TbkItemInfoGetInfo.NTbkItem>> items = taoBaoService.getSearchItemIdDetail(itemids);
                        if (items != null && items.getStatus() == 200 && items.getData() != null) {

                            List<TbkItemInfoGetInfo.NTbkItem> nTbkItems = items.getData();

                            for (TbkItemInfoGetInfo.NTbkItem nTbkItem : nTbkItems) {
                                hasItemIdSet.add(nTbkItem.getNumIid() + "");
                                if (nTbkItem != null) {
                                    try {
                                        itemids = itemids.replace(nTbkItem.getNumIid() + ",", "");
                                        AppGoods appGoods_new = new AppGoods();
                                        appGoods_new.setTableId(map.get(nTbkItem.getNumIid() + "") == null ? 0 : map.get(nTbkItem.getNumIid() + "").getTableId());
                                        appGoods_new.setItemid(nTbkItem.getNumIid() + "");
                                        HaoDanKuItemInfo hdkRespones = taoBaoUtils.getHaoDanKuItemId(nTbkItem.getNumIid().toString());
                                        if (hdkRespones != null && hdkRespones.getData() != null) {
                                            AppGoods dataBean = HDKUtils.getAppGoodsFromHDK(hdkRespones.getData());
                                            appGoods_new = appGoodsService.getMoneyInfoByGoodsId(null, com, dataBean);
                                        } else {
                                            appGoods_new = appGoodsService.getMoneyInfoByGoodsId(nTbkItem, com, appGoods_new);
                                        }

                                        appGoods_new.setFanliUpdateTime((System.currentTimeMillis()) + "");

                                        //判断是否最终金额小于0
                                        BigDecimal itemendprice = new BigDecimal(appGoods_new.getItemendprice() == null ? 0d : appGoods_new.getItemendprice());
                                        BigDecimal tkMoney = new BigDecimal(appGoods_new.getTkmoney() == null ? "0" : appGoods_new.getTkmoney());


                                        //判断优惠卷是否过期需要删除
                                        boolean isNeedDelete = false;
                                        try {
                                            //获取当前时间
                                            Long str = Long.valueOf(DateFormatUtils.stampToDate1(System.currentTimeMillis()));
                                            //获取优惠券结束时间，如果优惠券已经过去，直接删除。
                                            Long str2 = Long.valueOf(DateFormatUtils.stampToDate1(Long.valueOf(appGoods_new.getCouponendtime())));
                                            Long str3 = Long.valueOf(DateFormatUtils.stampToDate1(Long.valueOf(appGoods_new.getEndTime())));
                                            if (str2 < str && str3 < str && needDeleteStr.toString().indexOf(appGoods_new.getItemid()) == -1) {
                                                AppGoodsFailure appGoodsFailure = new AppGoodsFailure();
                                                appGoodsFailure.setDown_type(1);
                                                appGoodsFailure.setDown_time(System.currentTimeMillis() + "");
                                                appGoodsFailure.setItemid(appGoods_new.getItemid());
                                                needDeleteStr.append(appGoods_new.getItemid()).append(",");
                                                appGoodsFailures.add(appGoodsFailure);
                                                isNeedDelete = true;
                                            }
                                        } catch (Exception e) {

                                        }
                                        if ((itemendprice.subtract(tkMoney)).compareTo(new BigDecimal(0)) < 0) {
                                            continue;
                                        }
                                        if (!isNeedDelete) {
                                            appGoodsUpdates.add(appGoods_new);

                                            String itemShortTitle = map.get(appGoods_new.getItemid()).getItemshorttitle();
                                            String itemTitle = map.get(appGoods_new.getItemid()).getItemtitle();
                                            String itemDesc = map.get(appGoods_new.getItemid()).getItemdesc();
                                            String itempic = map.get(appGoods_new.getItemid()).getItempic();
                                            appGoods_new.setItemshorttitle(itemShortTitle);
                                            appGoods_new.setItemtitle(itemTitle);
                                            appGoods_new.setItemdesc(itemDesc);
                                            appGoods_new.setItempic(itempic);
                                            if (!StringUtils.stringEquals(map.get(appGoods_new.getItemid()).getTkmoney(), appGoods_new.getTkmoney())) {
                                                appGoodsIndexUpdates.add(appGoods_new);
                                            } else if (!StringUtils.stringEquals(map.get(appGoods_new.getItemid()).getItemprice(), appGoods_new.getItemprice())) {
                                                appGoodsIndexUpdates.add(appGoods_new);
                                            } else if (!StringUtils.stringEquals(map.get(appGoods_new.getItemid()).getCouponendtime(), appGoods_new.getCouponendtime())) {
                                                appGoodsIndexUpdates.add(appGoods_new);
                                            } else if (!StringUtils.stringEquals(map.get(appGoods_new.getItemid()).getCouponstarttime(), appGoods_new.getCouponstarttime())) {
                                                appGoodsIndexUpdates.add(appGoods_new);
                                            } else if (!StringUtils.stringEquals(map.get(appGoods_new.getItemid()).getTkrates(), appGoods_new.getTkrates())) {
                                                appGoodsIndexUpdates.add(appGoods_new);
                                            } else if (!StringUtils.stringEquals(map.get(appGoods_new.getItemid()).getCouponmoney() + "", appGoods_new.getCouponmoney() + "")) {
                                                appGoodsIndexUpdates.add(appGoods_new);
                                            } else if (!StringUtils.stringEquals(map.get(appGoods_new.getItemid()).getTkmoney(), appGoods_new.getTkmoney())) {
                                                appGoodsIndexUpdates.add(appGoods_new);
                                            } else if (!StringUtils.stringEquals(map.get(appGoods_new.getItemid()).getItemsale() + "", appGoods_new.getItemsale() + "")) {
                                                appGoodsIndexUpdates.add(appGoods_new);
                                            } else if (!StringUtils.stringEquals(map.get(appGoods_new.getItemid()).getItemsale2() + "", appGoods_new.getItemsale2() + "")) {
                                                appGoodsIndexUpdates.add(appGoods_new);
                                            } else if (!StringUtils.stringEquals(map.get(appGoods_new.getItemid()).getTodaysale() + "", appGoods_new.getTodaysale() + "")) {
                                                appGoodsIndexUpdates.add(appGoods_new);
                                            } else if (!StringUtils.stringEquals(map.get(appGoods_new.getItemid()).getItemendprice() + "", appGoods_new.getItemendprice() + "")) {
                                                appGoodsIndexUpdates.add(appGoods_new);
                                            } else if (!StringUtils.stringEquals(map.get(appGoods_new.getItemid()).getCouponnum(), appGoods_new.getCouponnum())) {
                                                appGoodsIndexUpdates.add(appGoods_new);
                                            }

                                        }

                                    } catch (Exception e) {
                                        log.error("更新商品的优惠券金额失败   0 0/5 * * * ?  appGoods={}", JSON.toJSONString(appGoods));
                                    }
                                }
                            }
                        }
                        Set<String> itemIdSet = null;
                        //获取查不到的商品id
                        if (itemids != null && itemids != "") {
                            String[] result = itemids.split(",");
                            itemIdSet = new HashSet<>(Arrays.asList(result));
                            itemIdSet.removeAll(hasItemIdSet);
                            for (String itemid : itemIdSet) {
                                needDeleteStr.append(itemid).append(",");
                            }
                        }


                        for (String key : map.keySet()) {
                            if (!hasItemIdSet.contains(key)) {
                                if (map.get(key).getCouponmoney() <= 0.0d || (items != null && items.getStatus() == 200)) {
                                    AppGoodsFailure appGoodsFailure = new AppGoodsFailure();
                                    appGoodsFailure.setDown_type(1);
                                    appGoodsFailure.setDown_time(System.currentTimeMillis() + "");
                                    appGoodsFailure.setItemid(key);
                                    if (needDeleteStr.toString().indexOf(key) == -1) {

                                        needDeleteStr.append(key).append(",");
                                        appGoodsFailures.add(appGoodsFailure);
                                        log.info("更新商品的优惠券金额未查到商品itemId=" + key);
                                    }
                                }
                            }
                        }

                        itemids = "";//商品id集合用于查询，每次最多40个
                        map.clear();//商品id和tableid对照map
                        map = new HashMap<>();
                        hasItemIdSet.clear();
                        hasItemIdSet = new HashSet<>();
                    }
                }
            }
            if (appGoodsUpdates.size() > 0) {
                boolean flag = appGoodsService.updateBatchById(appGoodsUpdates);

                if (flag) {
//                    if (appGoodsIndexUpdates.size() > 0) {
//                        for (AppGoods appGoods : appGoodsIndexUpdates) {
//                            try {
//                                //更新索引
//                                appGoodsService.updateIndex(appGoods, "update");
//                            } catch (Exception e) {
//                                e.printStackTrace();
//                            }
//                        }
//                    }
                    log.info("更新商品的优惠券金额成功   0 0/5 * * * ?  flag={}  size={}", flag, appGoodsUpdates.size());
                } else {
                    log.info("更新商品的优惠券金额失败   0 0/5 * * * ?  flag={}  size={}", flag, appGoodsUpdates.size());
                }
            }

            if ((needDeleteStr != null && needDeleteStr.toString().length() > 1) || needDeleteStr.length() > 1) {

                //删除缓存app_fixedSortGoods_list中商品的固定排序
                String fixedSort_key = "app_fixedSortGoods_list";
                if (redisTemplateService.hasKey(fixedSort_key)) {
                    String[] itemids = Convert.toStrArray(needDeleteStr.toString());
                    for (int i = 0; i < itemids.length - 1; i++) {
                        redisTemplateService.delMapField(fixedSort_key, itemids[i]);
                    }
                }
                //将失效商品信息存入redis
                String nowDateHour = "failureAppGoods" + DateFormatUtils.getNowDateHour(new Date());

                String cc = needDeleteStr.toString().replaceAll(",", "").replaceAll(" ", "");
                if (needDeleteStr.toString().length() > 1 && cc.length() > 1) {

                    int i = appGoodsService.deleteAppGoodsByItemid(needDeleteStr.toString());

                    if (i > 0) {
                        int ii = syLabelGoodsService.deleteByItemIds(needDeleteStr.toString());
                        if (appGoodsFailures != null && appGoodsFailures.size() > 0) {
                            //将失效商品信息存入redis
                            redisTemplate.opsForList().rightPushAll(nowDateHour, appGoodsFailures);
                        }

//                        appGoodsService.deleteIndex(needDeleteStr.toString(), "delete");
                        log.info("更新商品的优惠券金额成功 检测失效商品   message商品表数据删除成功{}--ids={}", i, needDeleteStr.toString());
                    } else {
                        log.info("更新商品的优惠券金额成功 检测失效商品   message商品表数据删除失败{}", i);
                    }
                }
                List<AppGoods> appGoodsList = appGoodsMapper.selectRecommendGoodsAll();
                taoBaoService.getRedisRecommendGoodsList(appGoodsList);
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.info("更新商品的优惠券金额 每5分钟一次错误");
        }
        long endTime = System.currentTimeMillis();
        log.info("***************************************结束更新商品的优惠券金额 每5分钟一次-HdkItemTask：executeCount=" + executeCount + "--endTime=" + endTime + "--耗时=" + (endTime - startTime));

    }


    /**
     * 判断是不是今天
     *
     * @param s
     * @param s2
     * @return
     */
    private Boolean isToDay(Long s, Long s2) {

        return DateUtils.isSameDay(new Date(s), new Date(s2));
    }

    /**
     * 通过开关判断是否要发消息
     *
     * @return
     * @id 开关类型
     */
    private Boolean isSendMsg(int id) {
        //查询开关表是否发消息
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("table_id", id);
        SySwitch sySwitch = iSySwitchService.getOne(queryWrapper);
        if (sySwitch == null) return false;
        if (sySwitch.getState() == 1) {
            log.info("消息类型{} 消息开发送消息", id);
            return true;
        }
        log.info("消息类型{} 消息关", id);
        return false;
    }
}
